package com.sccba.emtbusiness.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.sccba.common.annotation.DataScope;
import com.sccba.common.exception.GlobalException;
import com.sccba.common.exception.ServiceException;
import com.sccba.common.utils.DateUtils;
import com.sccba.common.utils.SecurityUtils;
import com.sccba.common.utils.StringUtils;
import com.sccba.emtbusiness.domain.YjczFbChannel;
import com.sccba.emtbusiness.service.IYjczUserChannelService;
import com.sccba.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sccba.emtbusiness.mapper.YjczChannelInfoMapper;
import com.sccba.emtbusiness.domain.YjczChannelInfo;
import com.sccba.emtbusiness.service.IYjczChannelInfoService;

/**
 * 应用系统Service业务层处理
 * 
 * @author lichh
 * @date 2024-04-15
 */
@Service
public class YjczChannelInfoServiceImpl implements IYjczChannelInfoService 
{
    private static final Logger log = LoggerFactory.getLogger(YjczChannelInfoServiceImpl.class);

    @Autowired
    private YjczChannelInfoMapper yjczChannelInfoMapper;

    @Autowired
    private IYjczUserChannelService yjczUserChannelService;

    /**
     * 查询应用系统
     * 
     * @param pkId 应用系统主键
     * @return 应用系统
     */
    @Override
    public YjczChannelInfo selectYjczChannelInfoByPkId(Long pkId)
    {
        return yjczChannelInfoMapper.selectYjczChannelInfoByPkId(pkId);
    }

    /**
     * 查询应用系统列表
     * 
     * @param yjczChannelInfo 应用系统
     * @return 应用系统
     */
    @Override
    public List<YjczChannelInfo> selectYjczChannelInfoList(YjczChannelInfo yjczChannelInfo)
    {
        return yjczChannelInfoMapper.selectYjczChannelInfoList(yjczChannelInfo);
    }

    /**
     * 新增应用系统
     * 
     * @param yjczChannelInfo 应用系统
     * @return 结果
     */
    @Override
    public int insertYjczChannelInfo(YjczChannelInfo yjczChannelInfo)
    {
        checkChannelName(yjczChannelInfo.getChannelName(), null);
        yjczChannelInfo.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        yjczChannelInfo.setCreateTime(DateUtils.getNowDate());
        int i = yjczChannelInfoMapper.insertYjczChannelInfo(yjczChannelInfo);
        yjczUserChannelService.insertOrUpdateUserChannel(yjczChannelInfo.getPkId(), yjczChannelInfo.getChannelUserId(), yjczChannelInfo.getChannelUserIds(), true);
        return i;
    }

    /**
     * 修改应用系统
     * 
     * @param yjczChannelInfo 应用系统
     * @return 结果
     */
    @Override
    public int updateYjczChannelInfo(YjczChannelInfo yjczChannelInfo)
    {
        checkChannelName(yjczChannelInfo.getChannelName(), yjczChannelInfo.getPkId());
        yjczChannelInfo.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        yjczChannelInfo.setUpdateTime(DateUtils.getNowDate());
        int i = yjczChannelInfoMapper.updateYjczChannelInfo(yjczChannelInfo);
        yjczUserChannelService.insertOrUpdateUserChannel(yjczChannelInfo.getPkId(), yjczChannelInfo.getChannelUserId(), yjczChannelInfo.getChannelUserIds(), false);
        return i;
    }

    private void checkChannelName (String channelName, Long pkId) {
        int count = yjczChannelInfoMapper.selectCountByName(channelName, pkId);
        if (count > 0) {
            throw new ServiceException("系统名称不能重复，请修改后重新提交");
        }
    }

    /**
     * 批量删除应用系统
     * 
     * @param pkIds 需要删除的应用系统主键
     * @return 结果
     */
    @Override
    public int deleteYjczChannelInfoByPkIds(Long[] pkIds)
    {
        yjczUserChannelService.deleteByChannelIds(pkIds);
        return yjczChannelInfoMapper.deleteYjczChannelInfoByPkIds(pkIds);
    }

    /**
     * 删除应用系统信息
     * 
     * @param pkId 应用系统主键
     * @return 结果
     */
    @Override
    public int deleteYjczChannelInfoByPkId(Long pkId)
    {
        return yjczChannelInfoMapper.deleteYjczChannelInfoByPkId(pkId);
    }

    @Override
//    @DataScope(scopeByChannel = true, channelAlias = "b")
    public List<YjczChannelInfo> selectChannelListByFbId(YjczFbChannel yjczFbChannel) {
        return yjczChannelInfoMapper.selectChannelListByFbId(yjczFbChannel);
    }

    @Override
    public String importChannel(List<YjczChannelInfo> channelInfoList, Boolean isUpdateSupport, String operName) {
        if (null == channelInfoList || channelInfoList.isEmpty()) {
            throw new ServiceException("需要导入的数据为空，请检查并完善表格文件");
        }
        List<YjczChannelInfo> allList = yjczChannelInfoMapper.selectAllChannelList();
        Map<String, YjczChannelInfo> channelNameMap = allList.stream().collect(Collectors.toMap(YjczChannelInfo::getChannelName, Function.identity()));
        Map<String, YjczChannelInfo> channelCodeMap = allList.stream().collect(Collectors.toMap(YjczChannelInfo::getChannelCode, Function.identity()));
        List<String> currChannelNameList = new ArrayList<>();
        List<String> currChannelCodeList = new ArrayList<>();
        YjczChannelInfo yjczChannelInfo;
        List<YjczChannelInfo> insertList = new ArrayList<>();
        List<YjczChannelInfo> updateList = new ArrayList<>();
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder successMsg = new StringBuilder();
        int successNum = 0;
        int length = channelInfoList.size();
        YjczChannelInfo info;
        for (int i = 0; i < length; ++ i) {
            try {
                info = channelInfoList.get(i);
                String channelName = info.getChannelName();
                String channelCode = info.getChannelCode();
                if (currChannelNameList.contains(channelName) || currChannelCodeList.contains(channelCode)) {
                    continue;
                }
                if (null == (yjczChannelInfo = channelNameMap.get(channelName)) && null == (yjczChannelInfo = channelCodeMap.get(channelCode))) {
                    yjczChannelInfo = new YjczChannelInfo();
                    yjczChannelInfo.setCreateBy(operName);
                    yjczChannelInfo.setCreateTime(new Date());
                    yjczChannelInfo.setChannelGroup("110");
                    insertList.add(yjczChannelInfo);
                } else {
                    yjczChannelInfo.setUpdateBy(operName);
                    yjczChannelInfo.setUpdateTime(new Date());
                    updateList.add(yjczChannelInfo);
                }
                yjczChannelInfo.setChannelName(channelName);
                yjczChannelInfo.setChannelCode(channelCode);
                currChannelNameList.add(channelName);
                currChannelCodeList.add(channelCode);
                successNum ++;
            } catch (Exception e) {
                failureNum ++;
                String msg = StringUtils.format("<br/>第{}条数据导入失败，失败原因为：{}", i, e.getMessage());
                failureMsg.append(msg);
                log.error(msg);
            }
        }
        if (!insertList.isEmpty()) {
            yjczChannelInfoMapper.batchInsert(insertList);
        }
        if (!updateList.isEmpty() && isUpdateSupport) {
            yjczChannelInfoMapper.batchUpdate(updateList);
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public List<YjczChannelInfo> selectAllChannelList() {
        return yjczChannelInfoMapper.selectAllChannelList();
    }
}
